package service;

import java.util.Date;

import bean.Support;
import dao.SupportDAOImpl;
import dao.UserDAOImpl;

public class SupportService {

    public static final int SUPPORT_SUCCESS = 0;
    public static final int SUPPORT_ERROR_EXCEED = 1;
    public static final Object SUPPORT_LOCK = new Object();
    
    private SupportDAOImpl supportDAOImpl;
    private UserDAOImpl userDAOImpl;

    public void setSupportDAOImpl(SupportDAOImpl supportDAOImpl) {
        this.supportDAOImpl = supportDAOImpl;
    }
    
    public void setUserDAOImpl(UserDAOImpl userDAOImpl) {
        this.userDAOImpl = userDAOImpl;
    }

    /**
     * 投票
     * @param supporter 投票者
     * @param candidate 被支持者
     * @return 执行结果 0 成功 1 超过最大数量
     */
    public int support(String supporter, String candidate) {
        Date todayDate = new Date();
        int count = 0;
        synchronized (SUPPORT_LOCK) {
            count = supportDAOImpl.getTodaySupportCount(supporter, todayDate);
        }
        if (count >= 3) {
            return SUPPORT_ERROR_EXCEED;
        } else {
            supportDAOImpl.save(new Support(supporter, candidate, todayDate));
            userDAOImpl.addSupport(candidate);
            return SUPPORT_SUCCESS;
        }
    }
    
}
